'use strict'

const Service = require('egg').Service

class StoreService extends Service {

    /**
     * 查询接口service
     * @param offset
     * @param limit
     * @param search
     * @param isPage
     * @returns {Promise<*>}
     */
    async index(offset = 0,limit = 10,search = '',isPage = 'true',center_id = ''){
        const {app,ctx,service} = this;
        //定义查询参数
        if(!app.lodash.isEmpty(search)){
            search = ` and (a.name like '%${search}%' or a.realname like '%${search}%' or a.phone like '%${search}%') `;
        }
        if(!app.lodash.isEmpty(center_id)){
             center_id = ` and a.center_id = '${center_id}' `;
        }
        //判断是否分页
        let limit_sql = '';
        if(isPage == 'true'){
            limit_sql = ` limit ${offset},${limit} `;
        }else if(center_id == ''){
            let redis_data = await app.sessionStore.get('store_list');
            if(!app.lodash.isEmpty(redis_data)){
                return redis_data;
            }
        }
        let sql = `
            select 
            a.*,b.name as center_name
            from fd_store a
            left join fd_center b on b.id = a.center_id
            where a.deleted = '0' and b.deleted = '0'
            ${search}${center_id}
            order by a.created_at desc,a.center_id desc
            ${limit_sql}
        `;
        let count_sql = `
            select count(*) as total
            from fd_store a
            left join fd_center b on b.id = a.center_id
            where a.deleted = '0' and b.deleted = '0'
            ${search}${center_id}
        `;

        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        let count = 0;

         //redis缓存
        //判断是否分页
        if(isPage != 'true'){
            await app.sessionStore.set('store_list',{rows:data,count:count});
        }else{
            count = await ctx.model.query(count_sql,sequelize_query_param);
            count = count[0].total;
        }

        //返回结果
        return {rows:data,count:count};
    }

    /**
     * 新建接口service
     * @param param
     * @returns {Promise<*>}
     */
    async create(param){
        const {app,ctx,service} = this;
        //引入uuid生成器
        var uuid = require('node-uuid');

        //开启事务
        let t = await ctx.model.transaction();
        try {
            //定义新增的对象
            let store = {
                id:uuid.v1(),
                ...param,
                deleted: '0'
            };
            //调用sequelize新增对象 findOrCreate 将返回一个数组[对象，新增成功与否的布尔] 如果新增对象已存在，则返回该对象和false 否则返回新增对象和true
            let rs = await ctx.model.FdStore.findOrCreate({where:{name:store.name,center_id:store.center_id},defaults:store,transaction:t});

            //提交事务
            t.commit();

            //清空此模块的redis缓存
            app.sessionStore.destroy('store_list');

            //新增此对象的redis缓存
            app.sessionStore.set('store_'+store.id,rs[0]);

            //返回新增结果
            return rs[1];

        }catch (e) {
            //若出错 回滚
            t.rollback();
            //抛出出错信息
            ctx.throw(500,e.message)
        }
    }

    /**
     * 删除接口service
     * @param param
     * @returns {Promise<boolean>}
     */
    async destroy(param){
        const {app,ctx,service} = this;
        //开启事务
        let t = await ctx.model.transaction();
        try {
            //更新要删除对象的deleted字段为1 采取逻辑删除
            let rs = await ctx.model.FdStore.update({deleted:'1'},{where:{id:param.id},transaction:t});
            //rs返回影响的数据行数

            //提交事务
            t.commit();

            //清空此模块的redis缓存
            app.sessionStore.destroy('store_list');

            //删除此id的redis缓存
            app.sessionStore.destroy('store_'+param.id);

            //判断删除结果 若成功，则为1
            if(rs[0] === 1){
                return true;
            }else{
                return false;
            }

        }catch (e) {
            //失败 回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }
    }

    /**
     * 单一数据查询接口service
     * @param param
     * @returns {Promise<*>}
     */
    async show(param){
        const {app,ctx,service} = this;
        let redis_store = await app.sessionStore.get('store_'+param.id);
        if(!app.lodash.isEmpty(redis_store)){
            return redis_store;
        }
        //调用sequelize查询 findOne 只返回查询接口的第一个
        let rs = await ctx.model.FdStore.findOne({where:{id:param.id,deleted:'0'}});

        await app.sessionStore.set('store_'+param.id,rs);

        return rs;
    }

    /**
     * 更新接口service
     * @param param
     * @returns {Promise<boolean>}
     */
    async update(param){
        const {app,ctx,service} = this;
        //开启事务
        let t = await ctx.model.transaction();
        try {
            //调用sequelize update更新为批量更新 只要满足where条件的数据都将被更新
            let rs = await ctx.model.FdStore.update(param,{where:{id:param.id},transaction:t});
            //rs返回影响的数据行数

            //提交事务
            t.commit();

            //清空此模块的redis缓存
            app.sessionStore.destroy('store_list');

            //删除此id的redis缓存
            app.sessionStore.destroy('store_'+param.id);

            //判断结果
            if(rs[0] === 1){
                return true;
            }else{
                return false;
            }

        }catch (e) {
            //失败回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }
    }
}

module.exports = StoreService
